﻿#if NETSTANDARD2_0 || NETCOREAPP3_0
using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
#endif
using PetaPoco;

namespace Longbow.Data
{
    /// <summary>
    /// 数据库适配操作类
    /// </summary>
    internal class DefaultDbAdapter : IDbAdapter
    {
#if NETSTANDARD2_0 || NETCOREAPP3_0
        private readonly IConfiguration _configuration;
        private static readonly Func<IConfiguration, string, string> ConnectionStringResolve = (c, name) => string.IsNullOrEmpty(name)
            ? c.GetSection("ConnectionStrings").GetChildren().FirstOrDefault()?.Value
            : c.GetConnectionString(name);

        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="configuration">IConfiguration 实例</param>
        public DefaultDbAdapter(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 创建 IDatabase 实例方法
        /// </summary>
        /// <param name="name">连接字符串名称</param>
        /// <param name="keepAlive">是否保持Connection一直处于Open状态，此参数为True时必须显示手动调用Dispose方法</param>
        /// <returns>IDatabase 实例</returns>
        public IDatabase Create(string name = null, bool keepAlive = false)
        {
            var option = RetrieveDatabaseOption(_configuration, name);
            option.KeepAlive = keepAlive;
            return Create(option);
        }

        /// <summary>
        /// 通过配置文件获得 DatabaseOption 实例
        /// </summary>
        /// <param name="configuration">IConfiguration 实例</param>
        /// <param name="name">连接字符串名称</param>
        /// <returns>DatabaseOption 实例</returns>
        internal static DatabaseOption RetrieveDatabaseOption(IConfiguration configuration, string name = null) => configuration.GetSection("DB").GetChildren()
                .Select(config => new
                {
                    Enabled = bool.TryParse(config["Enabled"], out var en) ? en : false,
                    Value = new DatabaseOption()
                    {
                        ProviderName = Enum.TryParse(config["ProviderName"], true, out DatabaseProviderType pn) ? pn : DatabaseProviderType.SqlServer,
                        ConnectionString = ConnectionStringResolve(config.GetSection("ConnectionStrings").Exists() ? config : configuration, name)
                    }
                }).FirstOrDefault(i => i.Enabled)?.Value ?? new DatabaseOption() { ConnectionString = ConnectionStringResolve(configuration, name) };

#else
        /// <summary>
        /// 创建 IDatabase 实例方法
        /// </summary>
        /// <param name="name">连接字符串名称</param>
        /// <param name="keepAlive">是否保持Connection一直处于Open状态，此参数为True时必须显示手动调用Dispose方法</param>
        /// <returns>IDatabase 实例</returns>
        public IDatabase Create(string name = null, bool keepAlive = false)
        {
            var option = new DatabaseOption() { KeepAlive = keepAlive };
            return Create(option);
        }
#endif

        /// <summary>
        /// 创建 IDatabase 实例方法
        /// </summary>
        /// <param name="option">DatabaseOption 实例</param>
        /// <returns>IDatabase 实例</returns>
        public static IDatabase Create(DatabaseOption option)
        {
            var source = DatabaseConfiguration.Build();

            // connectionstring
#if NETSTANDARD2_0 || NETCOREAPP3_0
            source.UsingConnectionString(option.ProviderName == DatabaseProviderType.SQLite ? option.ConnectionString.GetOSPlatformPath() : option.ConnectionString);
#else
            source.UsingConnectionString(option.ConnectionString);
#endif

            // provider
            source.UsingProviderName(option.ProviderName.ToString());
            return new Database(source) { KeepConnectionAlive = option.KeepAlive };
        }
    }
}
